package com.zr.bookcorner.presenter;

import android.content.Context;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;

import com.zh.baselibrary.base.BasePresenter;
import com.zh.baselibrary.constant.BaseConstant;
import com.zh.baselibrary.model.BookModel;
import com.zh.baselibrary.netutils.BaseResp;
import com.zh.baselibrary.rxjava.RxSubscribe;
import com.zh.baselibrary.utils.ComparatorUtils;
import com.zh.baselibrary.utils.JsonUtils;
import com.zh.baselibrary.utils.LogUtils;
import com.zh.baselibrary.utils.PhoneUtil;
import com.zh.baselibrary.utils.ShareManager;
import com.zh.baselibrary.utils.TTSUtils;
import com.zh.baselibrary.views.ToastView;
import com.zh.model.Errata;
import com.zh.model.manager.BookInfo;
import com.zh.model.request.SubmitDetailInfo;
import com.zh.model.request.SubmitInfo;
import com.zr.andealib.util.CheckBookMediumUtil;
import com.zr.andealib.util.CheckBookUtil;
import com.zr.andealib.util.LockUtil;
import com.zr.andealib.util.constant.CheckUtil;
import com.zr.andealib.util.model.InventoryReport;
import com.zr.bookcorner.BookApplication;
import com.zr.bookcorner.R;
import com.zr.bookcorner.constant.Constant;
import com.zr.bookcorner.presenter.view.OperateDetailView;
import com.zr.bookcorner.service.VoiceEvent;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.Semaphore;

import io.reactivex.Observable;

public class ManagerDetailPresenter extends BasePresenter<OperateDetailView> {
    protected BookModel model;
    private List<String> firstTime= new ArrayList<>();
    private List<String> lastTime = new ArrayList<>();
    private List<String> now = new ArrayList<>();
     int count = 0;
    private LockUtil lockUtil;
    private CheckUtil mCheckBookUtil;
     boolean isDoorClosed = false;

    private Timer timer;
    List<String> outList = new ArrayList<>();
    List<String> inList = new ArrayList<>();
    List<String> inThisList = new ArrayList<>();
    List<BookInfo> bookInList = new ArrayList<>();
    String schoolId;
    int boxNum;
    private List<BookInfo> upList = new ArrayList<>();
    private List<BookInfo> downList = new ArrayList<>();
    private List<BookInfo> notImportList = new ArrayList<>();
    private List<BookInfo> notSchoolList = new ArrayList<>();
    private List<BookInfo> notRelationList = new ArrayList<>();
    private List<BookInfo> returnList = new ArrayList<>();
    private StringBuilder normalDetail;
    private StringBuilder errorDetail;

    @Override
    public void attachModel(Context context) {
        super.attachModel(context);
        model = new BookModel(context);
        schoolId = ShareManager.getValue(context, BaseConstant.DEVICE_SCHOOL_ID);

    }

    public void initDevice(int boxNum) {
        this.boxNum = boxNum;
        String all = ShareManager.getValue(getContext(), Constant.BOX_DATA + boxNum);
        if(!TextUtils.isEmpty(all))
            firstTime = JsonUtils.stringToList(all, String.class);
        count = 0;
        new Thread(new Runnable() {
            @Override
            public void run() {
                //开始盘点
                if (mCheckBookUtil == null) {
                    if (BookApplication.isBig())
                        mCheckBookUtil = new CheckBookMediumUtil();
                    else
                        mCheckBookUtil = new CheckBookUtil();
                    mCheckBookUtil.init();
                    mCheckBookUtil.bookGridIdInventory(boxNum);
                }
                //

                checkDoorClose();
            }
        }).start();

        if (lockUtil == null) {
            lockUtil = new LockUtil();
            LogUtils.e("lockUtil赋值");
            lockUtil.init();
        }
    }

    void bookGridLater() {
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                if (mCheckBookUtil != null)
                    mCheckBookUtil.bookGridIdInventory(boxNum);
            }
        },200);

    }

    public void openDoor() {
         LogUtils.e("lockUtil为空?:"+(lockUtil==null));
        lockUtil.openDoor(boxNum);
    }

    public boolean isDoorOpen() {
        isDoorClosed = !lockUtil.isDoorOPen(boxNum);
        return !isDoorClosed;
    }

    //检测关门
    private void checkDoorClose() {
        if (timer == null)
            timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (lockUtil != null) {
                    boolean isOpen = lockUtil.isDoorOPen(boxNum);
                    if (!isOpen) {
                        isDoorClosed = true;
                           if (timer != null) {
                               timer.cancel();
                               timer.purge();
                               timer = null;
                           }
                    }
                }
            }
        }, 0, 100);
    }


    public void setDoorClosed(boolean doorClosed) {
        isDoorClosed = doorClosed;
    }

    public void onDestroy() {
        if(timer!=null){
            timer.cancel();
            timer.purge();
            timer = null;
        }
        if (lockUtil != null) {
            lockUtil.destory();
            lockUtil = null;
        }
        if (mCheckBookUtil != null) {
            mCheckBookUtil.destory();
            mCheckBookUtil = null;
        }

        BaseConstant.DEVICE_TOKEN2 = "";
    }

    public void doCheck(List<InventoryReport> listTags) {
        now.clear();
        outList.clear();
        inList.clear();
        inThisList.clear();
        List<String> outThisList = new ArrayList<>();
        for (InventoryReport listTag : listTags) {
            now.add(listTag.getUidStr());
        }
        if (count==0) {
             if(firstTime.size()==0&&now.size()!=0)
                 firstTime.addAll(now);
        } else {
            List<String> combine2List = new ArrayList<>(lastTime);
            combine2List.retainAll(now);  //交集
            inThisList.addAll(now);
            inThisList.removeAll(combine2List);   //新-交 = 增
            outThisList.addAll(lastTime);
            outThisList.removeAll(combine2List);   //旧-交 = 减
        }
        count++;
        //与上一次对其是否增减
        if (inThisList.size() == 0 && outThisList.size() == 0) {
             if(count!=1){
                if(isDoorClosed)
                    getView().doorClose();
                else
                    bookGridLater();
                return;
            }
        }
        //与第一次对比的增减
        List<String> combineList = new ArrayList<>(firstTime);
        combineList.retainAll(now);  //交集
        outList.addAll(firstTime);
        outList.removeAll(combineList);   //旧-交 = 减
        inList.addAll(now);
        inList.removeAll(combineList);   //新-交 = 增
        lastTime.clear();
        lastTime.addAll(now);
        getStatusFromNet();


    }

    //盘点到的+减少
    private void getStatusFromNet() {
        getView().loading();
        List<String> getList = new ArrayList<>();
        getList.addAll(now);
        getList.addAll(outList);
        LogUtils.e("first:"+JsonUtils.objectToString(firstTime));
        LogUtils.e("now:"+JsonUtils.objectToString(now));
        LogUtils.e("out:"+JsonUtils.objectToString(outList));
        LogUtils.e(JsonUtils.objectToString(getList));
        Observable<BaseResp<List<BookInfo>>> observable = getObservable(model.status(schoolId, getList));
        observable.subscribe(new RxSubscribe<BaseResp<List<BookInfo>>>() {
            @Override
            public void onSuccess(BaseResp<List<BookInfo>> baseResp) throws Exception {
                solveStatusFormNet(baseResp.getData());
            }

            @Override
            public void onHint(String hint) {
                bookGridLater();
            }
        });
    }

    protected void solveStatusFormNet(List<BookInfo> data) {
        upList.clear();
        downList.clear();
        notImportList.clear();
        notSchoolList.clear();
        notRelationList.clear();
        returnList.clear();
        bookInList.clear();
        normalDetail = new StringBuilder();
        errorDetail = new StringBuilder();
        boolean speak = false;
        for (BookInfo info : data) {
            if(inThisList.contains(info.getRadioCode())){
                if(info.getBookName().equals("未知书名")&& info.getStatus()!=7&&info.getStatus()!=8){
                    speak = true;
                }
            }
            if (outList.contains(info.getRadioCode())) { //减量 下架
                if(info.getStatus()!=7&&info.getStatus()!=8) {
                    info.setStatus(Constant.DOWN);
                    downList.add(info);
                    bookInList.add(info);
                }
            } else if (inList.contains(info.getRadioCode())) {
                if (info.getStatus() == Constant.UP) { //增量 无借阅还
                    info.setStatus(Constant.RETURN);
                    returnList.add(info);
                    continue;
                }
                bookInList.add(info);
                sort(info);//增量 分类
            }else if (info.getStatus()!=Constant.UP){ //全量 不为1 分类
                bookInList.add(info);
                sort(info);
            }else {  //全量为 1 未关联 已上架
                bookInList.add(info);
               if(info.getBookName().equals("未知书名")&& TextUtils.isEmpty(info.getImageUrl())){
                   notRelationList.add(info);
               }
            }

        }
        if(speak) {
           // TTSUtils.getInstance().speak(getContext().getString(R.string.tag_not_relation));
            EventBus.getDefault().post(new VoiceEvent(getContext().getString(R.string.tag_not_relation)));
        }
        detail();
        sortCabinet(bookInList);
        getView().getDataSuccess(bookInList);
        if(isDoorClosed&&(count!=1)) {
            LogUtils.e("count:"+count);
            getView().doorClose();
        }
        else
          bookGridLater();
    }
    private void sort(BookInfo info){
        int status = info.getStatus();
        if (status == Constant.NOT_UP) {
            upList.add(info);
        } else if (status == Constant.RETURN || status == Constant.RETURN6 ) {
            returnList.add(info);
        } else if (status == Constant.NOT_RELATION) {
            notRelationList.add(info);
            upList.add(info);
        } else if (status == Constant.NOT_IMPORT) {
            notImportList.add(info);
        } else if (status == Constant.NOT_SCHOOL) {
            notSchoolList.add(info);
        }
    }
    private void detail(){
        if(upList.size()!=0)
            normalDetail.append("已上架").append(changeColor(upList.size()+"")).append("本。");
        if(downList.size()!=0)
            normalDetail.append("已下架").append(changeColor(downList.size()+"")).append("本。");
        if(returnList.size()!=0)
            normalDetail.append("已还书").append(changeColor(returnList.size()+"")).append("本。");
        if(notImportList.size()!=0){
            errorDetail.append("标签号为");
            StringBuilder tagList = new StringBuilder();
            for(int i=0;i<notImportList.size();i++){
                tagList.append(notImportList.get(i).getRadioCode());
                if(i!=notImportList.size()-1)
                    tagList.append("、");
            }
            errorDetail.append(changeColor(tagList.toString())).append("异常，共").append(changeColor(notImportList.size()+"")).append("本，");
            errorDetail.append("异常原因：二维码未导入");
        }
        if(notSchoolList.size()!=0){
            errorDetail.append("标签号为");
            StringBuilder tagList = new StringBuilder();
            for(int i=0;i<notSchoolList.size();i++){
                tagList.append(notSchoolList.get(i).getRadioCode());
                if(i!=notSchoolList.size()-1)
                    tagList.append("、");
            }
            errorDetail.append(changeColor(tagList.toString())).append("异常，共").append(changeColor(notSchoolList.size()+"")).append("本，");
            errorDetail.append("异常原因：非本校书籍");
        }
        if(notRelationList.size()!=0){
            errorDetail.append("标签号为");
            StringBuilder tagList = new StringBuilder();
            for(int i=0;i<notRelationList.size();i++){
                tagList.append(notRelationList.get(i).getRadioCode());
                if(i!=notRelationList.size()-1)
                    tagList.append("、");
            }
            errorDetail.append(changeColor(tagList.toString())).append("异常，共").append(changeColor(notRelationList.size()+"")).append("本，");
            errorDetail.append("异常原因：二维码与书名未关联");
        }
    }
     String changeColor(String s) {
        return "<font color='#FF9026'>" +
                s +
                "</font>";
    }
    public String getAllTip(){
        return  normalDetail.toString()+errorDetail.toString();
    }
    public String getErrorTip(){
        return  errorDetail.toString();
    }
    public int getErrorSize(){
        return  notImportList.size()+notSchoolList.size()+notRelationList.size();
    }
    public void toSubmit() {
        SubmitInfo submitInfo = new SubmitInfo();
        String uuid = PhoneUtil.getUUID(getContext());
        List<SubmitDetailInfo> list = new ArrayList<>();

        for (BookInfo bookInfo : bookInList) {
            int status = bookInfo.getStatus();
            if (status == Constant.UP || status == Constant.NOT_IMPORT || status == Constant.NOT_SCHOOL) {
                continue;
            }
            if (status == Constant.NOT_UP||status == Constant.NOT_RELATION) {
                status = Constant.UP;
            }
            SubmitDetailInfo info = new SubmitDetailInfo();
            info.setRadioCode(bookInfo.getRadioCode());
            info.setStatus(status);
            list.add(info);
        }
        submitInfo.setCabinetNum(boxNum);
        submitInfo.setEquipmentCode(uuid);
        submitInfo.setBookList(list);
        submitOperate(submitInfo);
    }

    //勘误
    public void openError(int type) {
        isDoorClosed = false;
        checkDoorClose();
        mCheckBookUtil.bookGridIdInventory(boxNum); //重新盘点
        String uid = ShareManager.getValue(getContext(), Constant.LAST_USER_ID);
        String uidType = ShareManager.getValue(getContext(), Constant.LAST_USER_TYPE);
        Observable<BaseResp<Object>> observable = getObservable(model.errata(new Errata(schoolId,type,uid,uidType)));
        observable.subscribe(new RxSubscribe<BaseResp<Object>>() {
            @Override
            public void onSuccess(BaseResp<Object> objectBaseResp) throws Exception {
            }

            @Override
            public void onHint(String hint) {
            }
        });
    }

    void submitOperate(SubmitInfo submitInfo) {
        LogUtils.e(JsonUtils.objectToString(submitInfo));
        Observable<BaseResp<Object>> observable = getObservable(model.operate(schoolId, submitInfo));
        observable.subscribe(new RxSubscribe<BaseResp<Object>>() {
            @Override
            public void onSuccess(BaseResp<Object> objectBaseResp) throws Exception {
                ShareManager.setValue(getContext(), Constant.BOX_DATA + boxNum, JsonUtils.objectToString(now));
                ToastView.showShort("操作成功");
                getView().onSuccess(null);
            }

            @Override
            public void onHint(String hint) {
                getView().onHint(hint);

            }
        });
    }
    public String getName(int status) {
        StringBuilder sb = new StringBuilder();
        List<BookInfo> list = new ArrayList<>();
        if(status == Constant.UP)
            list = upList;
        else if(status == Constant.DOWN)
            list = downList;
        else  if (status == Constant.RETURN)
            list = returnList;
       for(int i = 0;i<list.size();i++){
           sb.append(list.get(i).getBookName());
           if(i!=list.size()-1)
               sb.append("、");
       }
       return sb.toString();
    }
     void sortCabinet(List<BookInfo> bookInList) {
        Collections.sort(bookInList, new Comparator<BookInfo>() {

            @Override
            public int compare(BookInfo o1, BookInfo o2) {

                if (o1.getStatus() == o2.getStatus()) {
                    return 0;
                } else {
                        if (o1.getStatus() == 1) {
                          return 1;
                        } else  {
                            if(o2.getStatus() ==1)
                                return  -1;
                           return  -(o1.getStatus() - o2.getStatus());
                        }
                }
            }
        });
    }

}
